/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package cassoftControllers;

import cassoftViews.Login;
import cassoftModels.Database;
import cassoftViews.MainView;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.JPasswordField;
import javax.swing.JTextField;

/**
 *  This class controls the login process.
 * @author Seamus
 */
public class LoginController {
    private Login login;
    private Database database;
    private ActionListener actionListener;
    
    /**
     * Constructor
     * @param login represents the login view.
     * @param database represents the database.
     */
    public LoginController(Login login, Database database){
        this.login = login;
        this.database = database;
        if (!database.initComponents()){
            JOptionPane.showMessageDialog(login, "Please connect the database and start again.");
            System.exit(0);
        }
    }
    /**
     * This method initiates the listeners.
     */
    public void control(){
        actionListener = new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                if(e.getSource() == login.getLoginBtn()){
                    login();
                }else if(e.getSource() == login.getExitBtn()){
                    exit();
                }
            }
        };
        
        login.getLoginBtn().addActionListener(actionListener);
        login.getExitBtn().addActionListener(actionListener);
    }
    
    /**
     * This method checks if user is in the database.
     */
    public void login(){
        JTextField userName = login.getUsername();
        JPasswordField passField = login.getPassword();
        System.out.println(passField);
        System.out.println(userName);
        char[] p = passField.getPassword();
        String pass = "";
        for(int i = 0; i<p.length;i++){
            pass = pass+p[i];
        }

        if(database.checkPassword(userName.getText(),pass)){
            login.dispose();
            MainView mainView = new MainView();
            MainController mc = new MainController(mainView, database);
            mc.control();
        }
            //System.out.println("Login is accessed.");
            //JOptionPane.showMessageDialog(login, "Login Successful");
        else
            //System.out.println("Login is failed");
            JOptionPane.showMessageDialog(login, "Login Failed");
    }
    
    /**
     * This method closes the view.
     */
    public void exit(){
        login.dispose();
    }
    
}
